package com.shallowUniverse.dmp.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.shallowUniverse.dmp.entity.Params;
import com.shallowUniverse.dmp.entity.Result;
import com.shallowUniverse.dmp.pojo.TableField;
import com.shallowUniverse.dmp.service.TableFieldService;
import com.shallowUniverse.dmp.utils.PageUtil;
import com.shallowUniverse.dmp.utils.ResultTool;
import com.shallowUniverse.dmp.utils.SidGenerator;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Shuai Guo
 * @version 1.0
 * @description
 * @date 2021/8/5
 */
@RestController
@RequestMapping("/tableFields")
public class TableFieldController {

    @Resource
    private TableFieldService tableFieldService;
    @Resource
    private SidGenerator sidGenerator;

    @GetMapping
    public Result<IPage<TableField>> findByPage(@RequestBody Params<TableField> params) {
        //返回数据
        return ResultTool.success(tableFieldService.page(PageUtil.build(params), lambda(params)));
    }

    @GetMapping("/list")
    public Result<List<TableField>> find(@RequestBody Params<TableField> params) {
        //返回数据
        return ResultTool.success(tableFieldService.list(lambda(params)));
    }

    @PostMapping
    public Result<Long> save(@RequestBody Params<TableField> params) {
        //设置sid
        params.getBody().setSid(sidGenerator.generate());
        //添加
        tableFieldService.save(params.getBody());
        //返回
        return ResultTool.success(params.getBody().getSid());
    }

    @PostMapping("/saveBatch")
    public Result<Long> saveBatch(@RequestBody Params<List<TableField>> params) {
        //批量设置sid
        params.getBody().forEach(tableField -> tableField.setSid(sidGenerator.generate()));
        //批量添加
        tableFieldService.saveBatch(params.getBody());
        //返回
        return ResultTool.success();
    }

    @PutMapping
    public Result<Long> update(@RequestBody Params<TableField> params) {
        //更新
        tableFieldService.updateById(params.getBody());
        //返回
        return ResultTool.success(params.getBody().getSid());
    }

    @DeleteMapping
    public Result<Long> delete(@RequestBody Params<List<Long>> params) {
        //删除数据源
        boolean result = tableFieldService.removeByIds(params.getBody());
        //返回
        return result ? ResultTool.success("删除成功") : ResultTool.fail("删除失败");
    }

    private LambdaQueryWrapper<TableField> lambda(Params<TableField> params) {
        //构造查询条件
        LambdaQueryWrapper<TableField> lambdaQueryWrapper = new QueryWrapper<TableField>().lambda();
        lambdaQueryWrapper.eq(TableField::getName, params.getBody().getName());
        return lambdaQueryWrapper;
    }
}
